package com.xinlan.imageeditlibrary.editimage.fragment;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.graphics.drawable.GradientDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.baselibrary.manager.LoadingManager;
import com.xinlan.imageeditlibrary.BaseEditFragment;
import com.xinlan.imageeditlibrary.EditImageFragment;
import com.xinlan.imageeditlibrary.R;
import com.xinlan.imageeditlibrary.editimage.ModuleConfig;
import com.xinlan.imageeditlibrary.editimage.model.OnBackPressedCallBack;
import com.xinlan.imageeditlibrary.editimage.model.RatioItem;
import com.xinlan.imageeditlibrary.editimage.utils.BitmapUtils;
import com.xinlan.imageeditlibrary.editimage.utils.DensityUtil;
import com.xinlan.imageeditlibrary.editimage.utils.DiaLogUtils;
import com.xinlan.imageeditlibrary.editimage.utils.Matrix3;
import com.xinlan.imageeditlibrary.editimage.view.CropImageView;
import com.xinlan.imageeditlibrary.editimage.view.imagezoom.ImageViewTouchBase;


/**
 * 图片剪裁Fragment
 *
 * @author panyi
 */
public class CropFragment extends BaseEditFragment implements OnClickListener {
    public static final int INDEX = ModuleConfig.INDEX_CROP;
    private View mainView;
    public CropImageView mCropPanel;// 剪裁操作面板
    private EditImageFragment mEditImageFragment;
    private Activity mActivity;

    static {
        ratioItemReduction = new RatioItem("原始", -1f);
        ratioItem1_1 = new RatioItem("1:1", 1f);
        ratioItem3_4 = new RatioItem("3:4", 3 / 4f);
        ratioItem4_3 = new RatioItem("4:3", 4 / 3f);
    }

    private OnBackPressedCallBack mOnBackCall;
    private ImageView mTvReduction;
    private TextView mTvCropReduction;
    private TextView mTvCrop4_3;
    private TextView mTvCrop3_4;
    private TextView mTvCrop1_1;
    private static RatioItem ratioItemReduction;
    private static RatioItem ratioItem1_1;
    private static RatioItem ratioItem3_4;
    private static RatioItem ratioItem4_3;
    private int mRotateAngle = 0;//纪录旋转角度
    private ImageView mIvCropClose;
    private ImageView mIvCropConfirm;

    private int cropType = 0;

    public static CropFragment newInstance(EditImageFragment mEditImageFragment) {
        CropFragment fragment = new CropFragment();
        fragment.setEditImageFragment(mEditImageFragment);
        fragment.setOnBackClick();
        return fragment;
    }


    public OnBackPressedCallBack getOnBackCall() {
        return mOnBackCall;
    }

    public void setOnBackClick() {
        mOnBackCall = new OnBackPressedCallBack() {
            @Override
            public void onBack() {
                initOriginal();
                backToMain();
            }
        };
    }

    public void setEditImageFragment(EditImageFragment mEditImageFragment) {
        this.mEditImageFragment = mEditImageFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mainView = inflater.inflate(R.layout.fragment_edit_image_crop, null);
        mActivity = getActivity();
        return mainView;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();

        if (id == R.id.tv_crop_1_1) {
            cropType = 1;
            mCropPanel.setVisibility(View.VISIBLE);
            mCropPanel.setRatioCropRect(mEditImageFragment.mainImage.getCropBitmapRect(), mEditImageFragment.mainImage.getBitmapRect(), ratioItem1_1.getRatio());//选择剪裁比率
            mTvCrop1_1.setSelected(true);
            mTvCrop3_4.setSelected(false);
            mTvCrop4_3.setSelected(false);
            GradientDrawable mGroupDrawable = (GradientDrawable) mTvCrop1_1.getBackground();
            mGroupDrawable.setStroke(DensityUtil.dip2px(mActivity, 1), Color.parseColor("#EE001E"));
            GradientDrawable mGroupDrawable3_4 = (GradientDrawable) mTvCrop3_4.getBackground();
            mGroupDrawable3_4.setStroke(DensityUtil.dip2px(mActivity, 1), Color.parseColor("#FFFFFF"));
            GradientDrawable mGroupDrawable4_3 = (GradientDrawable) mTvCrop4_3.getBackground();
            mGroupDrawable4_3.setStroke(DensityUtil.dip2px(mActivity, 1), Color.parseColor("#FFFFFF"));
        } else if (id == R.id.tv_crop_3_4) {
            cropType = 2;
            mCropPanel.setVisibility(View.VISIBLE);
            mCropPanel.setRatioCropRect(mEditImageFragment.mainImage.getCropBitmapRect(), mEditImageFragment.mainImage.getBitmapRect(), ratioItem3_4.getRatio());//选择剪裁比率
            mTvCrop1_1.setSelected(false);
            mTvCrop3_4.setSelected(true);
            mTvCrop4_3.setSelected(false);
            GradientDrawable mGroupDrawable = (GradientDrawable) mTvCrop1_1.getBackground();
            mGroupDrawable.setStroke(DensityUtil.dip2px(mActivity, 1), Color.parseColor("#FFFFFF"));
            GradientDrawable mGroupDrawable3_4 = (GradientDrawable) mTvCrop3_4.getBackground();
            mGroupDrawable3_4.setStroke(DensityUtil.dip2px(mActivity, 1), Color.parseColor("#EE001E"));
            GradientDrawable mGroupDrawable4_3 = (GradientDrawable) mTvCrop4_3.getBackground();
            mGroupDrawable4_3.setStroke(DensityUtil.dip2px(mActivity, 1), Color.parseColor("#FFFFFF"));
        } else if (id == R.id.tv_crop_4_3) {
            cropType = 3;
            mCropPanel.setVisibility(View.VISIBLE);
            mCropPanel.setRatioCropRect(mEditImageFragment.mainImage.getCropBitmapRect(), mEditImageFragment.mainImage.getBitmapRect(), ratioItem4_3.getRatio());//选择剪裁比率
            mTvCrop1_1.setSelected(false);
            mTvCrop3_4.setSelected(false);
            mTvCrop4_3.setSelected(true);
            GradientDrawable mGroupDrawable = (GradientDrawable) mTvCrop1_1.getBackground();
            mGroupDrawable.setStroke(DensityUtil.dip2px(mActivity, 1), Color.parseColor("#FFFFFF"));
            GradientDrawable mGroupDrawable3_4 = (GradientDrawable) mTvCrop3_4.getBackground();
            mGroupDrawable3_4.setStroke(DensityUtil.dip2px(mActivity, 1), Color.parseColor("#FFFFFF"));
            GradientDrawable mGroupDrawable4_3 = (GradientDrawable) mTvCrop4_3.getBackground();
            mGroupDrawable4_3.setStroke(DensityUtil.dip2px(mActivity, 1), Color.parseColor("#EE001E"));
        } else if (id == R.id.tv_crop_reduction) {
            initOriginal();
        } else if (id == R.id.iv_crop_confirm) {
            mTvCrop1_1.setSelected(false);
            mTvCrop3_4.setSelected(false);
            mTvCrop4_3.setSelected(false);
            GradientDrawable mGroupDrawable = (GradientDrawable) mTvCrop1_1.getBackground();
            mGroupDrawable.setStroke(DensityUtil.dip2px(mActivity, 1), Color.parseColor("#FFFFFF"));
            GradientDrawable mGroupDrawable3_4 = (GradientDrawable) mTvCrop3_4.getBackground();
            mGroupDrawable3_4.setStroke(DensityUtil.dip2px(mActivity, 1), Color.parseColor("#FFFFFF"));
            GradientDrawable mGroupDrawable4_3 = (GradientDrawable) mTvCrop4_3.getBackground();
            mGroupDrawable4_3.setStroke(DensityUtil.dip2px(mActivity, 1), Color.parseColor("#FFFFFF"));
            applyCropImage(true);
            mRotateAngle = 0;
        } else if (id == R.id.iv_crop_close) {
            View inflate = getLayoutInflater().inflate(R.layout.dialog_crop, null);
            final AlertDialog alertDialog = DiaLogUtils.showDialog(mActivity, inflate);
            inflate.findViewById(R.id.tv_dialog_confirm).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (alertDialog.isShowing())
                        alertDialog.dismiss();
                    initOriginal();
                    backToMain();
                }
            });
            inflate.findViewById(R.id.tv_dialog_cancel).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (alertDialog.isShowing())
                        alertDialog.dismiss();
                }
            });
        } else if (id == R.id.tv_reduction) {
            //mCropPanel.setVisibility(View.GONE);
            mRotateAngle = Matrix3.rotateImg(mRotateAngle);
            mEditImageFragment.changeMainBitmap(BitmapUtils.rotateBitmap(90, mEditImageFragment.getMainBit()), true);//转换一次替换Bitmap
            mCropPanel.post(new Runnable() {
                @Override
                public void run() {
                    mCropPanel.invalidate();
                    switch (cropType) {
                        case 1:
                            mCropPanel.setRatioCropRect(mEditImageFragment.mainImage.getCropBitmapRect(), mEditImageFragment.mainImage.getBitmapRect(), ratioItem1_1.getRatio());
                            break;
                        case 2:
                            mCropPanel.setRatioCropRect(mEditImageFragment.mainImage.getCropBitmapRect(), mEditImageFragment.mainImage.getBitmapRect(), ratioItem3_4.getRatio());
                            break;
                        case 3:
                            mCropPanel.setRatioCropRect(mEditImageFragment.mainImage.getCropBitmapRect(), mEditImageFragment.mainImage.getBitmapRect(), ratioItem4_3.getRatio());
                            break;
                    }
                }
            });
        }
    }

    public void initOriginal() {
        cropType = 0;
        mCropPanel.setVisibility(View.GONE);
        //选择剪裁比率
        mCropPanel.setRatioCropRect(mEditImageFragment.mainImage.getCropBitmapRect(), mEditImageFragment.mainImage.getBitmapRect(), -1);
        //图片归位
        mEditImageFragment.changeMainBitmap(BitmapUtils.rotateBitmap(360 - mRotateAngle, mEditImageFragment.getMainBit()), true);
        mRotateAngle = 0;
        mTvCrop1_1.setSelected(false);
        mTvCrop3_4.setSelected(false);
        mTvCrop4_3.setSelected(false);
        GradientDrawable mGroupDrawable = (GradientDrawable) mTvCrop1_1.getBackground();
        mGroupDrawable.setStroke(DensityUtil.dip2px(mActivity, 1), Color.parseColor("#FFFFFF"));
        GradientDrawable mGroupDrawable3_4 = (GradientDrawable) mTvCrop3_4.getBackground();
        mGroupDrawable3_4.setStroke(DensityUtil.dip2px(mActivity, 1), Color.parseColor("#FFFFFF"));
        GradientDrawable mGroupDrawable4_3 = (GradientDrawable) mTvCrop4_3.getBackground();
        mGroupDrawable4_3.setStroke(DensityUtil.dip2px(mActivity, 1), Color.parseColor("#FFFFFF"));
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initListener();
        if (mEditImageFragment != null) {
            this.mCropPanel = mEditImageFragment.mCropPanel;
        }
    }


    private void initView() {
        mTvReduction = mainView.findViewById(R.id.tv_reduction);
        mTvCropReduction = mainView.findViewById(R.id.tv_crop_reduction);
        mTvCrop1_1 = mainView.findViewById(R.id.tv_crop_1_1);
        mTvCrop3_4 = mainView.findViewById(R.id.tv_crop_3_4);
        mTvCrop4_3 = mainView.findViewById(R.id.tv_crop_4_3);
        mIvCropClose = mainView.findViewById(R.id.iv_crop_close);
        mIvCropConfirm = mainView.findViewById(R.id.iv_crop_confirm);
    }

    private void initListener() {
        mTvReduction.setOnClickListener(this);
        mTvCropReduction.setOnClickListener(this);
        mTvCrop1_1.setOnClickListener(this);
        mTvCrop3_4.setOnClickListener(this);
        mTvCrop4_3.setOnClickListener(this);
        mIvCropConfirm.setOnClickListener(this);
        mIvCropClose.setOnClickListener(this);

        if (mEditImageFragment != null && mEditImageFragment.mainImage != null) {
            mEditImageFragment.mainImage.setOnScaleChangeListener(new ImageViewTouchBase.OnScaleChangeListener() {
                @Override
                public void onScaleChange() {
                    mCropPanel.post(new Runnable() {
                        @Override
                        public void run() {
                            mCropPanel.invalidate();
                            mCropPanel.setImageRect(mEditImageFragment.mainImage.getBitmapRect());
                        }
                    });
                }
            });
        }
    }

    @Override
    public void onShow() {
//        mEditImageFragment.setCropMargin(true);
//        mEditImageFragment.mainImage.resetImage();
        mEditImageFragment.mode = EditImageFragment.MODE_CROP;
        mEditImageFragment.mainImage.setImageBitmap(mEditImageFragment.getMainBit());
        if (!mEditImageFragment.mainImage.getLongGraph()) {
            mEditImageFragment.mainImage.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
        }
//        mEditImageFragment.mainImage.setScaleEnabled(false);// 禁用缩放
        mEditImageFragment.mainImage.setScaleEnabled(true);// 禁用缩放
    }

    /**
     * 返回主菜单
     */
    @Override
    public void backToMain() {
//        mEditImageFragment.setCropMargin(false);
//        mEditImageFragment.mainImage.resetImage();
        mEditImageFragment.mode = EditImageFragment.MODE_NONE;
        mCropPanel.setVisibility(View.GONE);
        mEditImageFragment.mainImage.setScaleEnabled(true);// 恢复缩放功能
        mCropPanel.setRatioCropRect(mEditImageFragment.mainImage.getCropBitmapRect(), mEditImageFragment.mainImage.getBitmapRect(), -1);
        mEditImageFragment.mainImage.setVisibility(View.VISIBLE);
        mEditImageFragment.swFragment(0);
        mRotateAngle = 0;
    }

    /**
     * 保存剪切图片
     *
     * @param isToMain 根据isToMain 区别是
     */
    public void applyCropImage(boolean isToMain) {
        // System.out.println("保存剪切图片");

        if (mCropPanel.getVisibility() == View.GONE) {
            if (isToMain)
                backToMain();
            return;
        }
        CropImageTask task = new CropImageTask(isToMain);
        task.execute(mEditImageFragment.getMainBit());
    }

    /**
     * 图片剪裁生成 异步任务
     *
     * @author panyi
     */
    @SuppressLint("StaticFieldLeak")
    private final class CropImageTask extends AsyncTask<Bitmap, Void, Bitmap> {
        private boolean isToMain;

        public CropImageTask(boolean isToMain) {
            this.isToMain = isToMain;
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            LoadingManager.hideLoadingDialog(getActivity());
        }

        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        @Override
        protected void onCancelled(Bitmap result) {
            super.onCancelled(result);
            LoadingManager.hideLoadingDialog(getActivity());
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            LoadingManager.showLoadingDialog(getActivity());
        }

        @SuppressWarnings("WrongThread")
        @Override
        protected Bitmap doInBackground(Bitmap... params) {
            Bitmap resultBit = null;
            try {
                RectF cropRect = mCropPanel.getCropRect();// 剪切区域矩形
                Matrix touchMatrix = mEditImageFragment.mainImage.getImageViewMatrix();
                // Canvas canvas = new Canvas(resultBit);
                float[] data = new float[9];
                touchMatrix.getValues(data);// 底部图片变化记录矩阵原始数据
                Matrix3 cal = new Matrix3(data);// 辅助矩阵计算类
                Matrix3 inverseMatrix = cal.inverseMatrix();// 计算逆矩阵
                Matrix m = new Matrix();
                m.setValues(inverseMatrix.getValues());
                m.mapRect(cropRect);// 变化剪切矩形
          /*  if ((int) cropRect.height() <= 0 || (int) cropRect.top <= 0) {//裁剪超过比例
                return params[0];
            }*/
                // x must be >= 0
                resultBit = Bitmap.createBitmap(params[0],
                        (int) cropRect.left,
                        (int) cropRect.top,
                        (int) cropRect.width(),
                        (int) cropRect.height());
            } catch (Exception e) {
                e.printStackTrace();
            }

            //saveBitmap(resultBit, mEditImageFragment.saveFilePath);
            return resultBit;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            LoadingManager.hideLoadingDialog(getActivity());
            if (result == null)
                return;
            mEditImageFragment.changeMainBitmap(result, true);
            mEditImageFragment.mCropPanel.setCropRect(mEditImageFragment.mainImage.getCropBitmapRect());
            if (isToMain)
                backToMain();
        }
    }// end inner class

}
